import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

import '../provider/book_provider.dart';
import '../model/Book.dart';
import '../utils/show_novel.dart';
import '../widget/status_view.dart';

class ShelfPage extends StatefulWidget {
  const ShelfPage({super.key});

  @override
  State<ShelfPage> createState() => _ShelfPageState();
}

class _ShelfPageState extends State<ShelfPage> {
  late final StatusViewController _controller;

  @override
  void initState() {
    super.initState();
    // 初始化时加载书籍数据
    _controller = StatusViewController();
    _loadBooks();
  }

  // 加载书籍数据的方法
  Future<void> _loadBooks() async {
    _controller.showLoading();
    // 使用 Provider 刷新书籍数据
    final bookProvider = Provider.of<BookProvider>(context, listen: false);
    await bookProvider.refreshBooks();
    _controller.loaded();
  }

  // 构建书籍网格视图
  Widget _buildSourcePage(List<Book> books) {
    return AlignedGridView.count(
      crossAxisCount: 3,
      mainAxisSpacing: 4,
      crossAxisSpacing: 4,
      itemCount: books.length,
      itemBuilder: (context, index) {
        bool isEven = index.isEven;
        return ShowNovel(
          isEven: isEven,
          index: index,
          heightC: 180,
          book: books[index],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取 BookProvider
    final bookProvider = Provider.of<BookProvider>(context);
    final List<Book> books = bookProvider.books;

    return Scaffold(
      appBar: AppBar(
        title: const Text("书架"),
        actions: [
          // 悬停显示文字
          Tooltip(
            message: '导入书籍', // 鼠标悬停时显示的提示文字
            child: IconButton(
              onPressed: () async {
                _controller.showLoading();
                try {
                  await bookProvider.convertFromTxt(); // 调用转换方法
                } catch (e) {
                  print('Error: $e'); // 处理异常
                } finally {
                  _controller.loaded();
                }
              },
              icon: const Icon(Icons.add),
            ),
          ),
        ],
      ),
      body:StatusView(
        retry: _loadBooks,
        controller: _controller,
        builder:(context) => Column(
          children: [
            Expanded(
              child: _buildSourcePage(books), // 传递书籍列表
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 刷新按钮点击事件
          await _loadBooks(); // 异步刷新书籍数据
        },
        child: const Icon(Icons.refresh_rounded),
      ),
    );
  }
}